package com.canbot.u05.activity.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.bumptech.glide.Glide
import com.canbot.u05.R
import com.canbot.u05.activity.BaseActivityNoTitle
import com.canbot.u05.activity.free.MediaInfo
import com.canbot.u05.bean.Audio
import com.canbot.u05.bean.JsonResponse
import com.canbot.u05.helper.DialogBuildHelper
import com.canbot.u05.socket.IpMsgConst
import com.canbot.u05.utils.Logger
import com.canbot.u05.utils.OkHttpUtils
import kotlinx.android.synthetic.main.base_choose_video_activity.*
import kotlinx.android.synthetic.main.base_video_item.view.*
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by zmp on 2019/6/3 16:57
 * @author zmp
 * 音频选择界面
 */
class BaseChooseVideoActivity : BaseActivityNoTitle() {


    private lateinit var myAdapter: MyAdapter
    private var hintTip: DialogBuildHelper.HintTipBuilder? = null
    private var currentPosition: Int = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.base_choose_video_activity)
        initView()
        getData()
    }

    private fun getData() {
        showBaseLoadDialog()
        val url = "${IpMsgConst.HTTP_URL_CHEST}getVideoList"
        val hashMap = HashMap<String, String>()
        hashMap["path"] = "/two_video"
        OkHttpUtils.upLoadFile(url, hashMap, object : OkHttpUtils.OkHttpCallBack {
            override fun onSuccess(result: String) {
                Log.e("t", result)
                dismissBaseDialog()
                val strMsgBean = JSON.parseObject(result, JsonResponse::class.java)
                Logger.e("save", "onSuccess:" + "http://" + IpMsgConst.HEAD_SOCKET_HOST + ":7755/" + "strMsgBean.getRc()" + strMsgBean.rc)
                if (strMsgBean.rc == 0) {
                    val list = JSON.parseArray(strMsgBean.result.toString(), Audio::class.java)
                    list?.let {
                        runOnUiThread {
                            arr.clear()
                            arr.addAll(list)
                            myAdapter.notifyDataSetChanged()
                        }
                        return
                    }
                }
                showBaseHintDialog(getString(R.string.no_video_find), true)

            }

            override fun onFailure() {
                dismissBaseDialog()
                showBaseHintDialog(getString(R.string.service_error_hint), true)
            }
        })

    }

    val arr: ArrayList<Audio> = ArrayList()

    private fun initView() {
        back_btn_head.setOnClickListener {
            finish()
        }

        saveTextView.setOnClickListener {
            if (currentPosition != -1) {
                setResult(Activity.RESULT_OK, Intent()
                        .putExtra(BaseVoiceSetActivity.AUDIO_TYPE_KEY, MediaInfo.AUDIO_TYPE_VIDEO)
                        .putExtra(BaseVoiceSetActivity.AUDIO_PATH_OR_CONTENT, arr[currentPosition].path)
                        .putExtra(BaseVoiceSetActivity.AUDIO_SIMPLE_NAME_KEY, arr[currentPosition].name))
                finish()
            } else {
                showHintDialog(getString(R.string.no_video_find));
            }
        }

        voiceRecycleView.layoutManager = GridLayoutManager(this, 6)
        myAdapter = MyAdapter(this, arr)
        voiceRecycleView.adapter = myAdapter
    }

    private fun showHintDialog(content: String) {
        if (hintTip == null) {
            hintTip = DialogBuildHelper.createHintTipDialog(this)
                    .setClickListener(null, true)
        }
        hintTip?.setContent(content, Gravity.CENTER)?.show()
    }

    internal inner class MyAdapter(context: Context, var arr: ArrayList<Audio>) : RecyclerView.Adapter<MyHolder>() {

        private val layoutInflater: LayoutInflater = LayoutInflater.from(context)

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyHolder {
            val inflate = layoutInflater.inflate(R.layout.base_video_item, parent, false)
            return MyHolder(inflate)
        }

        override fun onBindViewHolder(holder: MyHolder, position: Int) {
            val audio = arr[position]
            holder.updateView(audio)
        }

        override fun getItemCount(): Int {
            return arr.size
        }

    }

    internal inner class MyHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {

        private var videoTextView: TextView = itemView.videoTextView
        private var videoCheckIv: ImageView = itemView.videoCheckIv
        private var videoImageView: ImageView = itemView.videoImageView

        init {
            itemView.setOnClickListener(this)

            itemView.setOnTouchListener { v, event ->
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        v.scaleX = 0.9F
                        v.scaleY = 0.9F
                    }
                    MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                        v.scaleX = 1F
                        v.scaleY = 1F
                    }
                }
                return@setOnTouchListener false
            }
        }

        override fun onClick(v: View) {
            if (currentPosition != adapterPosition) {
                currentPosition = adapterPosition
                myAdapter.notifyDataSetChanged()
            }
        }

        fun updateView(audio: Audio) {
            Glide.with(videoImageView)
                    .asDrawable()
                    .load("${IpMsgConst.HTTP_URL_CHEST}${audio.path.let {
                        it.replaceFirst("/two_video/", "/two_video_thumb/").removeRange(it.lastIndexOf('.') until it.length)
                    }
                    }.png")
                    .into(videoImageView)
            videoTextView.text = audio.name
            if (currentPosition != -1) {
                videoCheckIv.visibility = if (audio.path == arr[currentPosition].path) View.VISIBLE else View.GONE
            }
        }

    }

}